﻿using Autofac;
using CTM.Web.App_Start;
using CTM.Web.Services;
using CTM.Web.Utils;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Security;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using System.Data.Entity;
using log4net;
using System;
using System.Configuration;

namespace CTM.Web
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            // TODO - should comment when deploy to production
            //Database.SetInitializer(new ApplicationInitializer());

            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            //log4net.Config.XmlConfigurator.Configure();
            // Autofac and Automapper configurations
            Bootstrapper.Run();
        }

        protected void Session_Start()
        {
            var isSendMailToSupporter = Convert.ToBoolean(ConfigurationManager.AppSettings["SendMailToSupporterOnApplicationError"]);

            if (this.Context.User != null && this.Context.User.Identity.IsAuthenticated && !string.IsNullOrEmpty(this.Context.User.Identity.Name))
            {
                var authenticationType = Context.User.Identity.AuthenticationType;
                if (!string.IsNullOrEmpty(authenticationType) && authenticationType != "Forms" && authenticationType != "ApplicationCookie")
                {
                    try 
                    {
                        using (var container = CTM.Web.App_Start.Bootstrapper.ApplicationContainerBuider.BeginLifetimeScope())
                        {
                            var accountService = container.Resolve<IAccountService>();
                            var NTID = Context.User.Identity.Name.ToUpper();
                            if (NTID.IndexOf("\\") >= 0)
                            {
                                NTID = NTID.Split('\\').GetValue(1).ToString();
                            }
                            var user = accountService.Get(u => u.NTID.ToUpper() == NTID).FirstOrDefault();

                            if (user != null)
                            {
                                GlobalVariables.CurrentUser = user;
                            }
                        }
                    }
                    catch(System.Exception ex)
                    {
                        //log4net.LogManager.GetLogger(this.GetType()).Error(ex.Message, ex);
                        //var message = ex.ToMessageAndCompleteStacktrace();
                        var message = ex.GetAllExceptionInfo();

                        LogManager.GetLogger("ErrorLogger").Error(message);
                        if (isSendMailToSupporter)
                        {
                            LogManager.GetLogger("EmailLogger").Error(message);
                        }
                    }
                }
            }
        }

        protected void Application_Error(object sender, System.EventArgs e)
        {
            // Get the exception object.
            System.Exception exc = Server.GetLastError();

            //log4net.LogManager.GetLogger(this.GetType()).Error(exc.Message, exc);
            var isSendMailToSupporter = Convert.ToBoolean(ConfigurationManager.AppSettings["SendMailToSupporterOnApplicationError"]);
            //var message = exc.ToMessageAndCompleteStacktrace();
            var message = exc.GetAllExceptionInfo();

            LogManager.GetLogger("ErrorLogger").Error(message);
            if (isSendMailToSupporter)
            {
                LogManager.GetLogger("EmailLogger").Error(message);
            }
            
            Response.RedirectToRoute(
                            new RouteValueDictionary(
                                new
                                {
                                    controller = "Home",
                                    action = "Error"
                                })
                            );

            // Clear the error from the server
            Server.ClearError();
        }
    }
}
